package cn.edu.njust.epms.controller;

import cn.edu.njust.epms.entity.ATRecord;
import cn.edu.njust.epms.entity.ATResv;
import cn.edu.njust.epms.entity.User;
import cn.edu.njust.epms.entity.UserDetails;
import cn.edu.njust.epms.service.ATService;
import cn.edu.njust.epms.common.R;
import cn.edu.njust.epms.common.Resp;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/AcidTest")
public class ATController {
    @Autowired
    ATService as;

    /**
     * 添加核酸记录
     * @param record
     * @return
     */
    @PostMapping
    public Resp<ATRecord> acidTest(@RequestBody ATRecord record){
        return as.acidTest(record.getPid());
    }

    /**
     * 录入核酸结果
     * @param record
     * @return
     */
    @PutMapping
    public Resp<ATRecord> updateATResult(HttpServletRequest request,@RequestBody ATRecord record){
        User user = (User)request.getSession().getAttribute("user");
        if(user==null||user.getuSts()!=2){
            return Resp.error("拒绝访问");
        }
        return as.updateATResult(record);
    }


    /**
     * 条件查询
     * @param request
     * @param r
     * 传入参数r封装了前端的数据，当传入该参数为null，不对该参数进行筛选，传入参数非空，将使用该参数查询，传入全空时，返回完整结果
     * @return
     */
    @PostMapping("/list")
    public Resp<PageInfo<ATRecord>> selectByCondition(HttpServletRequest request, @RequestBody R r){
        System.out.println("411111");
        User user =(User)request.getSession().getAttribute("user");
        Integer uId = user.getuId();
        System.out.println(uId);
        if (user.getuSts() != 2)
            r.setuId(uId);
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="aId";
        if (r.getPageNo() != null) {
            _pageNo = r.getPageNo();
        }
        if (r.getSize() != null) {
            _size = r.getSize();
        }
        if (r.getOrder()!=null && r.getOrder().length()>0) {//没有传入排序，则默认以aId排序
            order = r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<ATRecord>> resp = as.selectByCondition(r);
        PageInfo<ATRecord> pageInfo = new PageInfo<>(resp.getData());
        return Resp.success(pageInfo);
    }

    /**
     * 下载/导出核酸检测记录表格
     * @param request
     * @param response
     */
    @GetMapping("list/download")
    public void export(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String,String> map){
        Integer uid = null;
        if (map.get("uId") != null)
            uid = Integer.valueOf(map.get("uId"));
        String pid =  map.get("pid");
        String name = map.get("name");
        String aResult = map.get("result");
        R r = new R();
        r.setuId(uid);
        r.setName(name);
        r.setPid(pid);
        if(aResult != null){
            if (aResult.equals("3")){
                r.setaResult(3);
            } else if (aResult.equals("4")) {
                r.setaResult(4);
            }
        }
        //新建HSSFWorkbook
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "AcidTest_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        Resp<List<ATRecord>> listResp = as.selectByCondition(r);
        List<ATRecord> data = listResp.getData();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,10*256);
        row0.createCell(0).setCellValue("核酸ID");
        row0.createCell(1).setCellValue("被采样人");
        row0.createCell(2).setCellValue("被采样人身份证号");
        row0.createCell(3).setCellValue("采样时间");
        row0.createCell(4).setCellValue("结果");
        for (int i = 1; i <= data.size(); i++) {
            ATRecord record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getaId());
            row.createCell(1).setCellValue(record.getUd().getName());
            row.createCell(2).setCellValue(record.getPid());
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            row.createCell(3).setCellValue(format.format(record.getaTime()));
            Integer _result = record.getaResult();
            String result;
            switch (_result){
                case 1:result = "已采样";
                        break;
                case 2:result = "待复核";
                    break;
                case 3:result = "阴性";
                    break;
                case 4:result = "阳性";
                    break;
                default:result = "未知";
            }
            row.createCell(4).setCellValue(result);
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加核酸预约信息
     * @param ar
     * @return
     */
    @PostMapping("/resv")
    public Resp<ATResv> acidTestResv(@RequestBody ATResv ar){
        return as.acidTestResv(ar);
    }

    /**
     * 修改预约状态
     * @param resv
     * @return
     */
    @PutMapping("/resv")
    public Resp<ATResv> updateATResv(HttpServletRequest request,@RequestBody ATResv resv){
//        User user = (User)request.getSession().getAttribute("user");
//        if(user==null||user.getuSts()!=2){
//            return Resp.error("拒绝访问");
//        }
        return as.updateATResv(resv);
    }


    /**
     * 展示预约记录
     * @param request
     * @param r
     * @return
     */
    @PostMapping("/resv/list")
    public Resp<PageInfo<ATResv>> selectResvByCondition(HttpServletRequest request, @RequestBody R r){
        User user =(User)request.getSession().getAttribute("user");
        Integer uId = user.getuId();
        if (user.getuSts() != 2)
            r.setuId(uId);
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="rId";
        if (r.getPageNo() != null) {
            _pageNo = Integer.valueOf(r.getPageNo());
        }
        if (r.getSize() != null) {
            _size = Integer.valueOf(r.getSize());
        }
        if (r.getOrder()!=null && r.getOrder().length()>0) {//没有传入排序，则默认以aId排序
            order = r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<ATResv>> resp = as.selectResvByCondition(r);
        PageInfo<ATResv> pageInfo = new PageInfo<>(resp.getData());
        return Resp.success(pageInfo);
    }

    /**
     * 核酸预约信息导出
     * @param request
     * @param response
     */
    @GetMapping("/resv/list/download")
    public void exportResv(HttpServletRequest request, HttpServletResponse response,@RequestParam Map map){

        //新建HSSFWorkbook
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "AcidTestResv_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        Resp<List<ATResv>> listResp = as.selectResvByCondition(new R());
        List<ATResv> data = listResp.getData();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,20*256);
        sheet1.setColumnWidth(5,10*256);
        row0.createCell(0).setCellValue("核酸预约ID");
        row0.createCell(1).setCellValue("申请人");
        row0.createCell(2).setCellValue("申请人人身份证号");
        row0.createCell(3).setCellValue("申请时间");
        row0.createCell(4).setCellValue("预约核酸时间");
        row0.createCell(5).setCellValue("预约状态");
        for (int i = 1; i <= data.size(); i++) {
            ATResv record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getrId());
            row.createCell(1).setCellValue(record.getUd().getName());
            row.createCell(2).setCellValue(record.getPid());
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            row.createCell(3).setCellValue(format.format(record.getrTime()));
            row.createCell(4).setCellValue(format.format(record.getaTime()));
            Integer _result = record.getSts();
            String result;
            switch (_result){
                case -1:result = "已撤销";
                    break;
                case 0:result = "已提交";
                    break;
                case 1:result = "已完成";
                    break;
                default:result = "未知";
            }
            row.createCell(5).setCellValue(result);
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除核酸记录
     * 慎用！！！
     * @param aId
     * @return
     */
    @DeleteMapping("/{aId}")
    public Resp<String> deleteATResult(HttpServletRequest request,@PathVariable Integer aId){
        User user = (User)request.getSession().getAttribute("user");
        if(user==null||user.getuSts()!=2){
            return Resp.error("拒绝访问");
        }
        Resp<String> resp = as.deleteATRecord(aId);
        return resp;
    }

    /**
     * 删除预约记录
     * 慎用！！！！
     * @param r
     * @return
     */
    @PostMapping("/resv/delete")
    public Resp<String> deleteATResv(HttpServletRequest request,@RequestBody ATResv r){
        User user = (User)request.getSession().getAttribute("user");
        if(user==null||user.getuSts()!=2){
            return Resp.error("拒绝访问");
        }
        Resp<String> resp = as.deleteATResv(r);
        return resp;
    }

    @GetMapping("/list/not_at")
    public void downloadNotReport(HttpServletResponse response){
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "notAT_"+new SimpleDateFormat("yyyyMMddHHmm").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        List<UserDetails> data = as.selectUdNotAT7day();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,24*256);
        row0.createCell(0).setCellValue("用户id");
        row0.createCell(1).setCellValue("姓名");
        row0.createCell(2).setCellValue("身份证号");
        row0.createCell(3).setCellValue("手机号");
        row0.createCell(4).setCellValue("地址");
        for (int i = 1; i <= data.size(); i++) {
            UserDetails record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getuId());
            row.createCell(1).setCellValue(record.getName());
            row.createCell(2).setCellValue(record.getPid());
            row.createCell(3).setCellValue(record.getPhone());
            row.createCell(4).setCellValue(record.getAddr());
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
